package jk.framework.spring.security.authorization;

import org.springframework.security.access.ConfigAttribute;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;


import static jk.framework.spring.security.authorization.SecurityResource.*;

/**
 * 动态权限控制
 * @author cuichao
 */
public class DynamicSecurityAttribute implements ConfigAttribute {

    private final String attribute;

    private final String strategy;

    private boolean allowIfEqualGrantedDeniedDecisions;

    public DynamicSecurityAttribute(String attribute) {
        this(attribute, AFFIRMATIVE_STRATEGY,false);
    }

    public DynamicSecurityAttribute(String attribute, String strategy , boolean allowIfEqualGrantedDeniedDecisions) {
        Assert.hasText(attribute, "You must provide a configuration attribute");
        this.attribute = attribute;
        this.allowIfEqualGrantedDeniedDecisions = allowIfEqualGrantedDeniedDecisions;

        if( StringUtils.isEmpty(strategy) ){
            this.strategy = AFFIRMATIVE_STRATEGY;
            return;
        }
        switch (strategy){
            case UNANIMOUS_STRATEGY :
                this.strategy = UNANIMOUS_STRATEGY;
            break;
            case CONSENSUS_STRATEGY :
                this.strategy = CONSENSUS_STRATEGY;
                break;
            case AFFIRMATIVE_STRATEGY :
                this.strategy = AFFIRMATIVE_STRATEGY;
                break;
            default:
                this.strategy = AFFIRMATIVE_STRATEGY;
        }
    }


    public boolean isAllowIfEqualGrantedDeniedDecisions() {
        return allowIfEqualGrantedDeniedDecisions;
    }

    public String getStrategy(){
        return this.strategy;
    }


    @Override
    public String getAttribute() {
        return this.attribute;
    }

    @Override
    public boolean equals(Object obj) {

        if (!(obj instanceof DynamicSecurityAttribute)) {
            return false ;
        }

        DynamicSecurityAttribute attr = (DynamicSecurityAttribute) obj;

        if(!this.attribute.equals(attr.getAttribute())){
            return false;
        }
        if(!this.strategy.equals(attr.getStrategy())){
            return false;
        }
        if(this.allowIfEqualGrantedDeniedDecisions != attr.isAllowIfEqualGrantedDeniedDecisions()){
            return false;
        }

        return true;
    }

    @Override
    public int hashCode() {
        return this.attribute.hashCode();
    }

    @Override
    public String toString() {
        return this.attribute;
    }




}
